﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Commerce.CSK.Web.Controls;
using Commerce.Data; 
namespace Commerce.CSK.Web
{
    public partial class Checkout : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                CartView ctl = CheckoutWizard.WizardSteps[0].FindControl("ReviewCart") as CartView;
                ReviewCart.CurrentOrder = Services.GetCurrentOrder(); 
                BillingAddressEntry.CurrentAddress = new Address();
                ShippingAddressEntry.CurrentAddress = new Address(); 
                
                
            }
        }


        protected void CheckoutWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            //TODO: Call as an async page request. 
            

            //Get the values. 
            Order crntOrder = Services.GetCurrentOrder();
            PopulateOrder(crntOrder);
            Services.GetOrderService().SaveOrder(crntOrder);
            Transaction trans = Services.GetPaymentService().Authorize(crntOrder);
            //TODO: Handle actual transactions. 
            Services.GetOrderService().SaveOrder(crntOrder); 
            
            
        }

        private void PopulateOrder(Order crntOrder)
        {
            crntOrder.ShippingAddress = ShippingAddressEntry.CurrentAddress;
            crntOrder.ShippingAddress.UserName = crntOrder.UserName;

            crntOrder.BillingAddress = BillingAddressEntry.CurrentAddress;
            crntOrder.BillingAddress.UserName = crntOrder.UserName;
            crntOrder.PaymentMethod = CreditCardEntry.CurrentPaymentMethod;
        }

        protected void CheckoutWizard_ActiveStepChanged(object sender, EventArgs e)
        {
            if(CheckoutWizard.ActiveStep.StepType == WizardStepType.Finish)
            {
                //This is the finish (review) step. 
                Order crntOrder = Services.GetCurrentOrder();
                //Populate from the controls for display, but don't save. 
                this.PopulateOrder(crntOrder); 
            }
        }

    }
}
